package com.yc.servlet;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.bean.FoodBean;
import com.yc.dao.FoodDao;
import com.yc.dao.OrderDao;
import com.yc.dao.OrderDetailDao;
import com.yc.util.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@WebServlet("/OrderList")
public class OrderServlet extends BaseServlet {
    private final ObjectMapper mapper = new ObjectMapper(); // Jackson ObjectMapper
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        // 从请求中读取 JSON 数据
        StringBuilder jsonPayload = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                jsonPayload.append(line);
            }
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write("Error reading JSON data from request: " + e.getMessage());
            return;
        }

        // 解析 JSON 数据
        JsonNode requestData;
        try {
            requestData = mapper.readTree(jsonPayload.toString());
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write("Invalid JSON payload: " + e.getMessage());
            return;
        }

        // 提取订单信息
        String tableId = requestData.path("dinnerTableId").asText();
        String totalPrice = requestData.path("totalPrice").asText();
        String userid=requestData.path("userid").asText();

        // 生成订单编号
        double totalPriceDouble = Double.parseDouble(totalPrice);
        int totalPriceInt = (int) totalPriceDouble; // 将浮点数转换为整数

        LocalDateTime now = LocalDateTime.now();
        String orderDateTime = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
        String orderCode = orderDateTime + tableId + totalPriceInt;

        // 调用 DAO 存储订单

        int orderid  = OrderDao.setOrderList(Integer.parseInt(userid),orderCode, Integer.parseInt(tableId), Double.parseDouble(totalPrice));

        if (orderid<0) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("Failed to save order to database.");
            return;
        }

        // 提取购物车中的菜品信息并存储订单详情
        JsonNode itemsArray = requestData.path("items");
        for (JsonNode itemNode : itemsArray) {
            int foodId = itemNode.path("id").asInt();
            int buyNum = itemNode.path("count").asInt();
            double discountPrice = itemNode.path("discount").asDouble();

            // 调用 DAO 存储订单详情
            boolean detailSaved = OrderDetailDao.setOrderDetail(orderid, foodId, buyNum, discountPrice);

            //更新食物的销量表
            FoodDao.update(foodId,buyNum);

            if (!detailSaved) {
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                resp.getWriter().write("Failed to save order details to database.");
                return;
            }
        }

        // 返回成功响应给前端
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().write("Order received and processed successfully: " + orderCode);
        }
    }


